
package com.kugou.game.sdk.ui.fragment;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.MobilePayRequestParams;
import com.kugou.game.sdk.entity.PayConstant.ChargeType;
import com.kugou.game.sdk.interfaces.OnCardPayListener;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.dialog.MobileRechargeConfirmDialog;
import com.kugou.game.sdk.ui.dialog.SelectOptionDialog;
import com.kugou.game.sdk.ui.dialog.SelectOptionDialog.OnSelectOptionListener;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.UUID;

/**
 * 描述:充值卡充值
 *
 * @author wcj
 * @since 2015年11月11日 下午5:37:55
 */
public class RechargeByMobileCardFragment extends BaseRechargeFragment implements OnClickListener {

    private final int PLATFORM = 0;

    private final int VALUE = 1;

    /**
     * 请求支付
     */
    private final int MSG_BACK_REQUEST_PAY = 2;

    /**
     * 开始加载
     */
    private final int MSG_START_LOADING = 3;

    /**
     * 请求支付成功
     */
    private final int MSG_PAY_SUCCESS = 4;

    /**
     * 请求支付失败
     */
    private final int MSG_PAY_FAILED = 5;

    private String[] platfroms = {
            "中国移动", "中国联通", "中国电信"
    };

    private int[] chinaMobileMoney = {
            10, 20, 30, 50, 100, 200, 300, 500
    };

    private int[] chinaUnicomMoney = {
            20, 30, 50, 100, 200, 300, 500
    };

    private int[] chinaTelecomMoney = {
            20, 30, 50, 100
    };

    /**
     * 1:中国移动；2：中国联通；3：中国电信。默认中国移动
     */
    private int mPhoneCardType = 1;

    private int mRechargeValueIndex = 0;

    private Context mContext;

    private TextView mRechargeErrorTipsTV;

    private Button mRechargeRatioBtn, mRechargePlatformBtn, mRechargeValueBtn, mRechargeSubmitBtn;

    private EditText mMobileCardSNCodET, mMobileCardPasswdET;

    /**
     * 保存用户选中的要进行兑换的值
     */
    private int mCurrentRechargeValue = 10;

    /** 支付的订单 */
    private String mOrderId;

    public static RechargeByMobileCardFragment getFragment(boolean rechargeYoubi) {
        RechargeByMobileCardFragment fragment = new RechargeByMobileCardFragment();
        fragment.mIsRechargeYoubi = rechargeYoubi;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = getActivity();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initViews();
        updateCanGotKubi();

        // mMobileCardSNCodET.setText("13278199228823652");
        // mMobileCardPasswdET.setText("393916597124673620");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        int layoutId = Rx.layout.kg_fragment_recharge_mobile_card;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            layoutId = Rx.layout.kg_fragment_recharge_mobile_card_land;
        }
        return inflater.inflate(layoutId, null);
    }

    private void initViews() {

        mRechargeRatioBtn = (Button) findViewById(Rx.id.kg_btn_recharge_ratio);
        mRechargeRatioBtn.setOnClickListener(this);

        mRechargePlatformBtn = (Button) findViewById(Rx.id.kg_btn_recharge_platform);
        mRechargePlatformBtn.setOnClickListener(this);

        mRechargeValueBtn = (Button) findViewById(Rx.id.kg_btn_recharge_value);
        mRechargeValueBtn.setOnClickListener(this);

        mRechargeSubmitBtn = (Button) findViewById(Rx.id.kg_btn_recharge_submit);
        mRechargeSubmitBtn.setOnClickListener(this);

        mRechargeErrorTipsTV = (TextView) findViewById(Rx.id.kg_tv_recharge_mobile_error_tips);

        mMobileCardSNCodET = (EditText) findViewById(Rx.id.kg_et_recharge_mobile_sn_code);
        mMobileCardSNCodET.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    mMobileCardSNCodET.setBackgroundResource(Rx.drawable.kg_shape_frame_blue);
                } else {
                    mMobileCardSNCodET.setBackgroundResource(Rx.drawable.kg_shape_frame_gray);
                }

                mMobileCardSNCodET.setPadding((int) (12 * getActivity().getResources()
                        .getDisplayMetrics().density), 0, 0, 0);
            }
        });

        mMobileCardPasswdET = (EditText) findViewById(Rx.id.kg_et_recharge_mobile_passwd);
        mMobileCardPasswdET.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    mMobileCardPasswdET.setBackgroundResource(Rx.drawable.kg_shape_frame_blue);
                } else {
                    mMobileCardPasswdET.setBackgroundResource(Rx.drawable.kg_shape_frame_gray);
                }

                mMobileCardPasswdET.setPadding((int) (12 * getActivity().getResources()
                        .getDisplayMetrics().density), 0, 0, 0);
            }
        });

        mCurrentRechargeValue = 10;
        mPhoneCardType = 1;
        mRechargeValueIndex = 0;

    }

    private void updateCanGotKubi() {
        if (mIsRechargeYoubi) {
            updateCanGotKubiTextView(mCurrentRechargeValue, ChargeType.TYPE_PHONE);
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mRechargeRatioBtn) {
            showRatioDialog();
        } else if (v == mRechargePlatformBtn) {
            showOptionDialog(PLATFORM);
        } else if (v == mRechargeValueBtn) {
            showOptionDialog(VALUE);
        } else if (v == mRechargeSubmitBtn) {
            if (!checkAll()) {
                return;
            }

            showConfirmDialog();
            // 发送统计--点击确认支付按钮
            sendClickConfirmRechargeBtnStatics(ChargeType.TYPE_PHONE, mCurrentRechargeValue);

        }
    }

    private void setEditTextFocus(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        showSoftInput();
    }

    private boolean checkAll() {
        return checkCardNumber() && checkPasswordNumber();
    }

    private boolean checkCardNumber() {
        String text = mMobileCardSNCodET.getText().toString();
        if (AppUtil.isCardNumberCorrect(text)) {
            return true;
        } else {
            mRechargeErrorTipsTV.setText("提示：充值卡号格式不正确");
            ToastUtil.showMsg("充值卡号格式不正确");
            setEditTextFocus(mMobileCardSNCodET);
            return false;
        }
    }

    private boolean checkPasswordNumber() {
        String text = mMobileCardPasswdET.getText().toString();
        if (AppUtil.isCardPasswordCorrect(text)) {
            return true;
        } else {
            mRechargeErrorTipsTV.setText("提示：密码格式不正确");
            ToastUtil.showMsg("密码格式不正确");
            setEditTextFocus(mMobileCardPasswdET);
            return false;
        }
    }

    private void showRatioDialog() {
        final BaseConfirmDialog dialog = new BaseConfirmDialog(getActivity());
        dialog.setCancelBtnVisibility(View.GONE);
        dialog.setOKBtnText("知道了");
        dialog.setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
        dialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setDialogTitle("兑换比例");
        dialog.setMessage(PayManager
                .getRechargeExchangeTip(ChargeType.TYPE_PHONE, mIsRechargeYoubi));
        dialog.show();
    }

    /**
     * 支付确认对话框
     */
    private void showConfirmDialog() {
        final MobileRechargeConfirmDialog dialog = new MobileRechargeConfirmDialog(getActivity());
        dialog.setRechargeInfo(
                platfroms[mPhoneCardType - 1],
                mCurrentRechargeValue,
                mIsRechargeYoubi ? PayManager.getExchangeNum(mCurrentRechargeValue,
                        ChargeType.TYPE_PHONE) : null);
        dialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                sendEmptyBackgroundMessage(MSG_BACK_REQUEST_PAY);
            }
        });
        dialog.show();
    }

    private void showOptionDialog(final int what) {
        SelectOptionDialog dialog = new SelectOptionDialog((Activity) mContext);
        ArrayList<String> options = new ArrayList<String>();

        if (what == PLATFORM) {
            dialog.setCurrentOptionIndex(mPhoneCardType - 1);
            dialog.setDialogTitle("请选择运营商");

            options.add(platfroms[0]);
            options.add(platfroms[1]);
            options.add(platfroms[2]);
        } else {
            dialog.setCurrentOptionIndex(mRechargeValueIndex);
            dialog.setDialogTitle("请选择面值");

            addOptions(options, mPhoneCardType);
        }
        dialog.addDatas(options);

        dialog.setOnSelectOptionListener(new OnSelectOptionListener() {

            @Override
            public void afterSelectUser(String option, int index) {
                if (what == PLATFORM) {
                    if (mPhoneCardType != index + 1) {
                        mPhoneCardType = index + 1;
                        mRechargePlatformBtn.setText(option);

                        mRechargeValueIndex = 0;
                        if (mPhoneCardType == 1) {
                            mRechargeValueBtn.setText(chinaMobileMoney[0] + "元");
                            mCurrentRechargeValue = chinaMobileMoney[0];
                        } else if (mPhoneCardType == 2) {
                            mRechargeValueBtn.setText(chinaUnicomMoney[0] + "元");
                            mCurrentRechargeValue = chinaUnicomMoney[0];
                        } else {
                            mRechargeValueBtn.setText(chinaTelecomMoney[0] + "元");
                            mCurrentRechargeValue = chinaTelecomMoney[0];
                        }
                    }

                } else {
                    mRechargeValueIndex = index;
                    mRechargeValueBtn.setText(option);

                    if (mPhoneCardType == 1) {
                        mCurrentRechargeValue = chinaMobileMoney[index];
                    } else if (mPhoneCardType == 2) {
                        mCurrentRechargeValue = chinaUnicomMoney[index];
                    } else {
                        mCurrentRechargeValue = chinaTelecomMoney[index];
                    }
                }

                updateCanGotKubi();
            }
        });
        dialog.setDialogDefaultSize();
        dialog.show();

    }

    private void addOptions(ArrayList<String> options, int type) {
        if (mPhoneCardType == 1) {
            addOptions(chinaMobileMoney, options);
        } else if (mPhoneCardType == 2) {
            addOptions(chinaUnicomMoney, options);
        } else if (mPhoneCardType == 3) {
            addOptions(chinaTelecomMoney, options);
        }

    }

    private void addOptions(int[] values, ArrayList<String> options) {
        for (int i = 0; i < values.length; i++) {
            options.add(values[i] + "元");
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);
        switch (msg.what) {
            case MSG_BACK_REQUEST_PAY:
                sendEmptyUiMessage(MSG_START_LOADING);
                payByMobileCard();
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }
        switch (msg.what) {
            case MSG_START_LOADING:
                showLoadingView();
                break;
            case MSG_PAY_SUCCESS:
                if (msg.obj != null && !TextUtils.isEmpty(msg.obj.toString())) {
                    // todo // 跳转到结果界面
                    if (msg.obj != null && !TextUtils.isEmpty(msg.obj.toString())) {
                        // 跳转到结果界面
                        if (getOnEventListener() != null) {
                            getOnEventListener().onCheckRechargeResult(msg.obj.toString(),
                                    mCurrentRechargeValue, ChargeType.TYPE_PHONE);
                        }
                    }
                }
                break;
            case MSG_PAY_FAILED:
                hideLoadingView();
                mRechargeErrorTipsTV.setText("提示：" + msg.obj.toString());
                ToastUtil.showMsg(msg.obj.toString());

                sendCancelRechargeStatics(msg.obj.toString());
                break;
            default:
                break;
        }
    }

    /**
     * 发送取消支付的统计
     */
    private void sendCancelRechargeStatics(String errormsg) {
        sendCancelRechargeStatics(ChargeType.TYPE_PHONE, mCurrentRechargeValue, mOrderId, 1,
                errormsg);
    }

    private void payByMobileCard() {
        MobilePayRequestParams requestParams = new MobilePayRequestParams();

        String orderid = SDKControler.createNewOrderId();
        if (mIsRechargeYoubi) {
            // 生成唯一字符串
            orderid = UUID.randomUUID().toString();
            requestParams.setDirectCharge(0);
        } else {
            requestParams.setDirectCharge(1);
        }

        User user = UserManager.getInstance().getCurrentUserInternal();
        requestParams.setUserName(user.getAccountName());
        requestParams.setChargeType(ChargeType.TYPE_PHONE);
        requestParams.setMoney(mCurrentRechargeValue * 100);
        requestParams.setOutOrderId(orderid);
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setPhoneCardId(mMobileCardSNCodET.getText().toString());
        requestParams.setPhoneCardPwd(mMobileCardPasswdET.getText().toString());
        requestParams.setPhoneCardType(String.valueOf(mPhoneCardType));
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());
        PayManager.payByMobileCard(requestParams, onMobilePayListener);
    }

    OnCardPayListener onMobilePayListener = new OnCardPayListener() {

        @Override
        public void onSuccess(String orderId) {
            Message msg = new Message();
            msg.what = MSG_PAY_SUCCESS;
            msg.obj = orderId;
            sendUiMessage(msg);
        }

        @Override
        public void onFailed(String errorMsg) {
            Message msg = new Message();
            msg.what = MSG_PAY_FAILED;
            msg.obj = errorMsg;
            sendUiMessageDelayed(msg, 1000);
        }
    };

}
